package com.swak.mybatis;

import java.util.List;

import org.junit.Test;

import com.swak.entity.Page;
import com.swak.entity.Parameters;
import com.swak.mybatis.entity.Goods;
import com.swak.mybatis.mapper.GoodsMapper;
import com.swak.persistence.QueryCondition;
import com.swak.persistence.QueryCondition.Criteria;
import com.swak.persistence.Selective;
import com.swak.persistence.proxy.ProxyFactory;

/**
 * MyBatis 通过注册 Mapper
 * 
 * @author lifeng
 * @date 2021年1月21日 上午10:46:41
 */
public class MybatisTest2 extends MyBatisTest {

	@Test
	public void test() {
		GoodsMapper goodsMapper = sqlSessionTemplate.getMapper(GoodsMapper.class);

		// 这种方式操作必须使用spring的环境
//		Goods goods = new Goods().setId(1L).get();
//		if (goods == null) {
//			goods = new Goods().setId(1L).setName("李锋").setRemarks("很棒").insert();
//		}

		Goods goods = goodsMapper.get(1L);
		if (goods == null) {
			goods = new Goods().setId(1L).setName("李锋").setRemarks("很棒");
			goodsMapper.insert(goods);
			goods = goodsMapper.get(1L);
		}
		System.out.println(goods.getName());

		goods = new Goods().setName("李锋4");
		goods = goodsMapper.getUnique(goods);
		System.out.println(goods);

		QueryCondition qc = new QueryCondition();
		Criteria criteria = qc.getCriteria();
		criteria.andEqualTo("ID", 1L);
		List<Goods> lists = goodsMapper.queryByCondition(qc);
		System.out.println(lists);

		// 改进版本的 Mapper
		System.out.println("################ 改进版本  ##############");
		GoodsMapper goodsMapperx = (GoodsMapper) ProxyFactory.newProxy(GoodsMapper.class, sqlSessionTemplate);
		goods = goodsMapperx.getSelective(Selective.of().select("ID").andEqualTo("ID", 1L));
		System.out.println("只查询ID: " + goods);

		goods = goodsMapperx.getSelective(Selective.of().select("ID").select("NAME").andEqualTo("ID", 1L));
		System.out.println("查询ID, NAME: " + goods);

		Parameters param = new Parameters();
		Page page = goodsMapperx.queryForPage(qc, param);
		System.out.println("分页查询数据：" + page.getData());

		page = goodsMapperx.queryForSelectivePage(Selective.of().select("ID").andEqualTo("ID", 1L), param);
		System.out.println("只查询ID， 分页查询数据：" + page.getData());
	}
}